﻿using ToolKitIESiteList.Library;
using ToolKitManagerIESiteList.UserControls;
using ToolKitManagerIESiteList.Util;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using System.Diagnostics.CodeAnalysis;
using System.Collections.Concurrent;
using System.ComponentModel;

namespace ToolKitManagerIESiteList
{
    public partial class FrmMain : Form
    {
        private bool Resizing = false;
        private ToolTip toolTip = new ToolTip();
        private FilterType CurrentFilter;
        private string CurrentFilterValue;
        private string CurrentFind;
        private int CurrentFindIndex;
        private AutoCompleteStringCollection HistoryFind;
        private BackgroundWorker BackWork;
        private string resultCheckVer;
        private bool SavedFile;

        [SuppressMessage("Microsoft.Reliability", "CA2000")]
        public FrmMain()
        {
            InitializeComponent();
            BackWork = new BackgroundWorker();
            BackWork.DoWork += BackWork_DoWork;
            BackWork.RunWorkerCompleted += BackWork_RunWorkerCompleted;
            NewNotify.Visible = false;
            CurrentFilter = FilterType.None;
            CurrentFilterValue = null;
            CurrentFind = string.Empty;
            CurrentFindIndex = -1;
            HistoryFind = new AutoCompleteStringCollection();
            openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            TxtFindtoolStrip.AutoCompleteCustomSource = HistoryFind;
            EmieDocument.ResetEnvironment();
            contextMenuDocMode.Items.Clear();
            foreach (string item in Enum.GetNames(typeof(CompatMode)))
            {
                var itmenu = new ToolStripMenuItem(item) { CheckOnClick = true };
                itmenu.Click += contextMenuDocMode_Click;
                contextMenuDocMode.Items.Add(itmenu);
            }
            contextMenuOpenIn.Items.Clear();
            foreach (var item in Enum.GetNames(typeof(OpenIn)))
            {
                var itmenu = new ToolStripMenuItem(item) { CheckOnClick = true };
                itmenu.Click += contextMenuOpenIn_Click;
                contextMenuOpenIn.Items.Add(itmenu);
            }
        }

        private void BackWork_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (!string.IsNullOrEmpty(resultCheckVer))
            {
                NewNotify.Visible = true;
            }
        }

        private void BackWork_DoWork(object sender, DoWorkEventArgs e)
        {
            System.Threading.Thread.Sleep(10000);
            resultCheckVer = AssemblyHelper.CheckVersion();
        }

        private void contextMenuDocMode_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem item in listViewDataUrl.SelectedItems)
            {
                item.SubItems[1].Text = ((ToolStripMenuItem)sender).Text;
                var itemdata = (IEModeDataItem)item.Tag;
                var found = EmieDocument.GetDataItems().First(i => i == itemdata);
                found.CompatMode = (CompatMode)Enum.Parse(typeof(CompatMode), item.SubItems[1].Text);
                EmieDocument.UpdateCompatMode(found);
                item.Tag = found;
            }
            ShowSummary();
            EnsureState();
        }

        private void contextMenuOpenIn_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem item in listViewDataUrl.SelectedItems)
            {
                item.SubItems[2].Text = ((ToolStripMenuItem)sender).Text;
                var itemdata = (IEModeDataItem)item.Tag;
                var found = EmieDocument.GetDataItems().First(i => i == itemdata);
                found.OpenIn = (OpenIn)Enum.Parse(typeof(OpenIn), item.SubItems[2].Text);
                EmieDocument.UpdateOpenIn(found);
                item.Tag = found;
            }
            ShowSummary();
            EnsureState();
        }

        [SuppressMessage("Microsoft.Maintainability", "CA1502")]
        private void EnsureState()
        {
            var oldcur = this.Cursor;
            this.Cursor = Cursors.WaitCursor;

            var qtddup = EmieDocument.CountSiteDuplicate();
            var qtdp80 = EmieDocument.CountPort80();

            FindnextToolStripMenuItem.Enabled = !string.IsNullOrEmpty(CurrentFind);
            FindpreviousToolStripMenuItem.Enabled = !string.IsNullOrEmpty(CurrentFind);
            if (listViewDataUrl.Items.Count == 0)
            {
                TxtFindtoolStrip.Text = string.Empty;
                TxtFindtoolStrip.Enabled = false;
                toolStripButtonFind.Enabled = false;
            }
            else
            {
                TxtFindtoolStrip.Enabled = true;
                toolStripButtonFind.Enabled = true;
            }

            if (qtddup > 0)
            {
                LblSummary.Image = Properties.Resources.error;
                toolTip.SetToolTip(LblSummary, Properties.Resources.ErrorDocNotSaved);
            }
            else
            {
                LblSummary.Image = null;
                toolTip.SetToolTip(LblSummary, string.Empty);
            }
            switch (CurrentFilter)
            {
                case FilterType.None:
                    toolStripLblFilterCustom.Text = string.Empty;
                    break;
                case FilterType.CompatMode:
                    toolStripLblFilterCustom.Text = string.Format("{0}:{1}", Properties.Resources.CompatModeList, CurrentFilterValue);
                    break;
                case FilterType.OpenIn:
                    toolStripLblFilterCustom.Text = string.Format("{0}:{1}", Properties.Resources.OpenInList, CurrentFilterValue);
                    break;
                case FilterType.Duplicate:
                    toolStripLblFilterCustom.Text = Properties.Resources.DuplicateSites;
                    break;
                case FilterType.Port80:
                    toolStripLblFilterCustom.Text = Properties.Resources.SitesPort80Declared;
                    break;
                case FilterType.Custom:
                    break;
                default:
                    break;
            }
            PctClearFilter.Enabled = (CurrentFilter != FilterType.None);
            toolStripButtonRemoveP80.Enabled = (qtdp80 > 0);
            removeSpecificPort80ToolStripMenuItem.Enabled = (qtdp80 > 0);

            var qtdsites = EmieDocument.CountSites();
            simplifyingListOfSitesToolStripMenuItem.Enabled = (qtdsites > 0);
            toolStripButtonSimplifying.Enabled = (qtdsites > 0);
            toolStripButtonDomains.Enabled = (qtdsites > 0);
            removeDomainsToolStripMenuItem.Enabled = (qtdsites > 0);
            saveToolStripMenuItem.Enabled = (qtddup == 0 && qtdsites > 0);
            toolStripButtonSave.Enabled = (qtddup == 0 && qtdsites > 0);
            copyLocalDomainToPublicDomainToolStripMenuItem.Enabled = (qtdsites > 0);
            toolStripButtonCopyDomains.Enabled = (qtdsites > 0);
            customFiltersToolStripMenuItem.Enabled = (qtdsites > 0);
            if (qtdsites == 0)
            {
                customFiltersToolStripMenuItem.Image = Properties.Resources.filter_dis;

            }
            else
            {
                customFiltersToolStripMenuItem.Image = CurrentFilter == FilterType.Custom ?
                    Properties.Resources.filter_on : Properties.Resources.filter_off;
            }
            if (CurrentFilter != FilterType.Custom)
            {
                foreach (ToolStripMenuItem item in customFiltersToolStripMenuItem.DropDownItems)
                {
                    item.Checked = false;
                }
            }
            foreach (var item in flowLayoutSummary.Controls)
            {
                var ctr = item as ImageAndLabel;
                if (ctr != null)
                {
                    ctr.FilterOn = false;
                    if (CurrentFilter == FilterType.CompatMode && ctr.Filter == FilterType.CompatMode)
                    {
                        ctr.FilterOn = (CurrentFilterValue == ctr.Tag.ToString());
                    }
                    if (CurrentFilter == FilterType.OpenIn && ctr.Filter == FilterType.OpenIn)
                    {
                        ctr.FilterOn = (CurrentFilterValue == ctr.Tag.ToString());
                    }
                    if (CurrentFilter == FilterType.Duplicate && ctr.Filter == FilterType.Duplicate)
                    {
                        ctr.FilterOn = true;
                    }
                    if (CurrentFilter == FilterType.Port80 && ctr.Filter == FilterType.Port80)
                    {
                        ctr.FilterOn = true;
                    }
                }
            }
            clearHistoryToolStripMenuItem.Enabled = (HistoryFind.Count > 0);
            trackerActionToolStripMenuItem.Visible = Properties.Settings.Default.EnableHotTracker;
            toolStripSeparatorTracker.Visible = Properties.Settings.Default.EnableHotTracker;
            var qtd = listViewDataUrl.SelectedIndices.Count;
            toolStripButtonEditItem.Enabled = (qtd == 1);
            toolStripButtonRemoveItem.Enabled = (qtd >= 1);
            this.Cursor = oldcur;
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            ListView_SizeChanged(listViewDataUrl, e);

            ManagerHotTracker.TrackerEnable(Properties.Settings.Default.EnableHotTracker);

            Text = String.Format("{0} ({1})", AssemblyHelper.AssemblyTitle, AssemblyHelper.AssemblyVersion);

            toolStripStatus.Text = Properties.Resources.UnselectedFile;
            toolStripStatusSpace.Text = string.Empty;
            toolStripStatusSpace.Spring = true;
            LblSummary.Text = Properties.Resources.Summary;

            enabledTrackerActionToolStripMenuItem.Checked = (Properties.Settings.Default.EnableHotTracker);
            updateDateCreatedOnSaveToolStripMenuItem.Checked = (Properties.Settings.Default.UpdateDateCreated);
            updateVersionOnSaveToolStripMenuItem.Checked = (Properties.Settings.Default.UpdateVersion);
            BackupOldVersionOnSaveToolStripMenuItem.Checked = (Properties.Settings.Default.BackupOldVersion);
            removePort80atFileToolStripMenuItem.Checked = (Properties.Settings.Default.RemoveP80);
            ShowSummary();
            EnsureState();
            BackWork.RunWorkerAsync();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!SavedFile && !string.IsNullOrEmpty(EmieDocument.FileNameEmieDocument))
            {
                if (this.ShowQuestion(Properties.Resources.ConfirmNotSave, AssemblyHelper.AssemblyTitle))
                {
                    saveToolStripMenuItem_Click(sender, e);
                }
            }
            ManagerHotTracker.Clear();
            Close();
        }

        [SuppressMessage("Microsoft.Design", "CA1031")]
        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!SavedFile && !string.IsNullOrEmpty(EmieDocument.FileNameEmieDocument))
            {
                if (this.ShowQuestion(Properties.Resources.ConfirmNotSave, AssemblyHelper.AssemblyTitle))
                {
                    saveToolStripMenuItem_Click(sender, e);
                }
            }
            openFileDialog.FileName = string.Empty;
            var result = openFileDialog.ShowDialog();
            if (result == DialogResult.OK)
            {
                try
                {
                    HelperEmie.ValidateSchemeSiteList(openFileDialog.FileName);
                }
                catch (Exception ex)
                {
                    this.ShowError(string.Format("{0}:{1}", Properties.Resources.ErrorValidateScheme, ex.Message), AssemblyHelper.AssemblyTitle);
                    return;
                }
                var oldcur = this.Cursor;
                try
                {
                    this.Cursor = Cursors.WaitCursor;
                    EmieDocument.ResetEnvironment();
                    EmieDocument.FileNameEmieDocument = openFileDialog.FileName;
                    EmieDocument.ProgressChange += EmieDocument_ProgressChange;

                    var mergeresult = EmieDocument.OpenFileV2EmieDocument(
                        EmieDocument.FileNameEmieDocument,
                        Properties.Settings.Default.RemoveP80,
                        Properties.Settings.Default.RemoveExtFilter?
                            Properties.Settings.Default.ExcludeExtension.Cast<string>().ToArray():
                            new string[]{ },
                        Properties.Settings.Default.RemoveDomFilter?
                            Properties.Settings.Default.ExcludeDomains.Cast<string>().ToArray():
                            new string[] { }
                        );
                    MainProgressBar.Value = 0;
                    EmieDocument.ProgressChange -= EmieDocument_ProgressChange;

                    ManagerHotTracker.AddTraker(ActionTracker.OpenFile, Properties.Resources.NewSites, EmieDocument.FileNameEmieDocument, mergeresult.NewItems);
                    if (mergeresult.ExcludeHost.Length > 0)
                    {
                        ManagerHotTracker.AddTraker(ActionTracker.OpenFile, Properties.Resources.RemoveDomainFilter, EmieDocument.FileNameEmieDocument, mergeresult.ExcludeHost);
                    }
                    if (mergeresult.ExcludeExt.Length > 0)
                    {
                        ManagerHotTracker.AddTraker(ActionTracker.OpenFile, Properties.Resources.RemoveExtensionFilter, EmieDocument.FileNameEmieDocument, mergeresult.ExcludeExt);
                    }
                    if (mergeresult.Port80.Length > 0)
                    {
                        ManagerHotTracker.AddTraker(ActionTracker.OpenFile, Properties.Resources.RemovePort80, EmieDocument.FileNameEmieDocument, mergeresult.Port80);
                    }
                    if (mergeresult.Duplicates.Length > 0)
                    {
                        ManagerHotTracker.AddTraker(ActionTracker.OpenFile, Properties.Resources.DuplicateSites, EmieDocument.FileNameEmieDocument, mergeresult.Duplicates);
                        this.Cursor = oldcur;
                        using (var frm = new FrmMerge())
                        {
                            frm.FileName = EmieDocument.FileNameEmieDocument;
                            frm.DataMeger = mergeresult;
                            frm.ShowOption = ImportOption.Duplicate;
                            frm.TitleWindows = Properties.Resources.OpenSiteList;
                            frm.ShowDialog(this);
                        }
                    }
                    this.Cursor = Cursors.WaitCursor;
                    ManagerFilter(FilterType.None, null);
                    ShowListUri();
                    ShowSummary();
                    EnsureState();
                    this.Cursor = oldcur;
                }
                catch (Exception ex)
                {
                    this.Cursor = oldcur;
                    this.ShowError(string.Format("{0}:{1}", Properties.Resources.ErrorReadFile, ex.Message), AssemblyHelper.AssemblyTitle);
                }
                this.Cursor = oldcur;
            }
        }

        private void EmieDocument_ProgressChange(object sender, ProgressEventArgs e)
        {
            if (e.value == 1)
            {
                MainProgressBar.Maximum = e.Maxvalue;
            }
            MainProgressBar.Value = e.value;
        }

        private void ListView_SizeChanged(object sender, EventArgs e)
        {
            // Don't allow overlapping of SizeChanged calls
            if (!Resizing)
            {
                // Set the resizing flag
                Resizing = true;

                ListView listView = sender as ListView;
                if (listView != null)
                {
                    float totalColumnWidth = 0;

                    // Get the sum of all column tags
                    for (int i = 0; i < listView.Columns.Count; i++)
                        totalColumnWidth += Convert.ToInt32(listView.Columns[i].Tag);

                    // Calculate the percentage of space each column should 
                    // occupy in reference to the other columns and then set the 
                    // width of the column to that percentage of the visible space.
                    for (int i = 0; i < listView.Columns.Count; i++)
                    {
                        float colPercentage = (Convert.ToInt32(listView.Columns[i].Tag) / totalColumnWidth);
                        listView.Columns[i].Width = (int)(colPercentage * listView.ClientRectangle.Width);
                    }
                }
            }
            // Clear the resizing flag
            Resizing = false;
        }

        private void ShowListUri()
        {
            ShowListUri(CurrentFilter, CurrentFilterValue);
            CurrentFind = string.Empty;
            CurrentFindIndex = -1;
            FindnextToolStripMenuItem.Enabled = !string.IsNullOrEmpty(CurrentFind);
            FindpreviousToolStripMenuItem.Enabled = !string.IsNullOrEmpty(CurrentFind);
            TxtFindtoolStrip.Text = string.Empty;
        }

        private void ShowListUri(FilterType filter, string value)
        {
            var oldcur = this.Cursor;
            this.Cursor = Cursors.WaitCursor;
            listViewDataUrl.SuspendLayout();
            listViewDataUrl.Items.Clear();
            listViewDataUrl.Groups.Clear();
            var grupoName = string.Empty;
            var listord = EmieDocument.GetDataItems(filter, value).OrderBy(l => l.Url);
            var modesites = new Dictionary<CompatMode, int>();
            var PosGroup = new Dictionary<string, int>();
            MainProgressBar.Maximum = listord.Count();
            var posprogress = 0;

            foreach (var item in listord)
            {
                posprogress++;
                MainProgressBar.Value = posprogress;
                if (grupoName != item.HostPort)
                {
                    if (!string.IsNullOrEmpty(grupoName))
                    {
                        var modes = "  (";
                        foreach (var mode in modesites)
                        {
                            modes += mode.Key + ":" + mode.Value.ToString() + " , ";
                        }
                        modes = modes.Substring(0, modes.Length - 3) + ") ";
                        var pos = listViewDataUrl.Groups.Add(new ListViewGroup(grupoName + modes, HorizontalAlignment.Left));
                        PosGroup.Add(grupoName, pos);
                    }
                    modesites = new Dictionary<CompatMode, int>();
                    grupoName = item.HostPort;
                }
                if (!modesites.ContainsKey(item.CompatMode))
                {
                    modesites.Add(item.CompatMode, 0);
                }
                modesites[item.CompatMode]++;
            }
            if (!string.IsNullOrEmpty(grupoName))
            {
                var modes = "  (";
                foreach (var mode in modesites)
                {
                    modes += mode.Key + ":" + mode.Value.ToString() + " , ";
                }
                modes = modes.Substring(0, modes.Length - 3) + ") ";
                var pos = listViewDataUrl.Groups.Add(new ListViewGroup(grupoName + modes, HorizontalAlignment.Left));
                PosGroup.Add(grupoName, pos);
            }
            MainProgressBar.Value = 0;
            posprogress = 0;
            foreach (var item in listord)
            {
                posprogress++;
                MainProgressBar.Value = posprogress;
                var key = item.HostPort;
                var pos = PosGroup[key];
                ListViewItem lvi = new ListViewItem(item.AbsolutePath == "/"?item.HostPort:item.Url);
                lvi.Tag = item;
                lvi.Group = listViewDataUrl.Groups[pos];
                lvi.SubItems.Add(item.CompatMode.ToString());
                lvi.SubItems.Add(item.OpenIn.ToString());
                if (EmieDocument.DuplicateItems.Any(s => s.Url.ToLower() == item.Url.ToLower()))
                {
                    lvi.ForeColor = Color.Red;
                }
                lvi.ToolTipText = Properties.Resources.UseRightMouse;
                listViewDataUrl.Items.Add(lvi);
            };
            listViewDataUrl.ResumeLayout();
            MainProgressBar.Value = 0;
            this.Cursor = oldcur;
        }

        [SuppressMessage("Microsoft.Reliability", "CA2000")]
        private void ShowSummary()
        {
            var oldcur = this.Cursor;
            this.Cursor = Cursors.WaitCursor;
            flowLayoutSummary.SuspendLayout();
            flowLayoutSummary.Controls.Clear();
            if (EmieDocument.GetDataItems().Count() == 0)
            {
                flowLayoutSummary.ResumeLayout();
            }

            var lbl = new Label()
            {
                AutoSize = true,
                Name = "LblSummaryDateCreated",
                Text = string.Format("{0}\n{1}", Properties.Resources.DateCreated, EmieDocument.DateCreatedEmieDocument),
                Padding = new Padding(3, 5, 3, 5),
                ForeColor = Color.White
            };
            flowLayoutSummary.Controls.Add(lbl);

            lbl = new Label()
            {
                AutoSize = true,
                Name = "LblSummaryVer",
                Text = string.Format("{0} : {1}", Properties.Resources.Version, EmieDocument.VersionEmieDocument),
                Padding = new Padding(3, 5, 3, 5),
                ForeColor = Color.White
            };
            flowLayoutSummary.Controls.Add(lbl);

            var qtddup = EmieDocument.CountSiteDuplicate();

            var itdup = new ImageAndLabel()
            {
                AutoSize = false,
                Width = flowLayoutSummary.Width - 30,
                Name = "LblDuplicate",
                Enabled = (qtddup > 0),
                FilterOn = (qtddup > 0 && CurrentFilter == FilterType.Duplicate),
                Text = string.Format("\t{0} : {1}", Properties.Resources.TotDuplicate, qtddup),
                ForeColor = Color.White,
                Filter = FilterType.Duplicate,
            };
            itdup.FilterClick += Itdup_FilterClick;
            flowLayoutSummary.Controls.Add(itdup);

            var qtdp80 = EmieDocument.CountPort80();

            var itp80 = new ImageAndLabel()
            {
                AutoSize = false,
                Width = flowLayoutSummary.Width - 30,
                Name = "LblPort80",
                Enabled = (qtdp80 > 0),
                FilterOn = (qtdp80 > 0 && CurrentFilter == FilterType.Port80),
                Text = string.Format("\t{0} : {1}", Properties.Resources.TotPort80, qtdp80),
                ForeColor = Color.White,
                Filter = FilterType.Port80,
            };
            itp80.FilterClick += Itp80_FilterClick;
            flowLayoutSummary.Controls.Add(itp80);

            lbl = new Label()
            {
                AutoSize = true,
                Name = "LblSummaryTitmode",
                Text = Properties.Resources.CompatModeList,
                Padding = new Padding(3, 5, 3, 5),
                ForeColor = Color.White
            };
            lbl.Font = new Font(lbl.Font.FontFamily, lbl.Font.Size, FontStyle.Bold);
            flowLayoutSummary.Controls.Add(lbl);

            foreach (var item in EmieDocument.StatsCompatMode)
            {
                var itFilter = new ImageAndLabel()
                {
                    AutoSize = false,
                    Width = flowLayoutSummary.Width - 30,
                    Name = string.Format("{0}{1}", "LblSummary", item.Key),
                    Text = string.Format("\t{0} : {1}", item.Key, item.Value),
                    ForeColor = Color.White,
                    Tag = item.Key,
                    Filter = FilterType.CompatMode
                };
                itFilter.FilterClick += FilterMode_FilterClick;
                flowLayoutSummary.Controls.Add(itFilter);
            }

            lbl = new Label()
            {
                AutoSize = true,
                Name = "LblSummaryTitOpenIn",
                Text = Properties.Resources.OpenInList,
                Padding = new Padding(3, 5, 3, 5),
                ForeColor = Color.White
            };
            lbl.Font = new Font(lbl.Font.FontFamily, lbl.Font.Size, FontStyle.Bold);
            flowLayoutSummary.Controls.Add(lbl);
            foreach (var item in EmieDocument.StatsOpenIn)
            {
                var itFilter = new ImageAndLabel()
                {
                    AutoSize = false,
                    Width = flowLayoutSummary.Width - 30,
                    Name = string.Format("{0}{1}", "LblSummary", item.Key),
                    Text = string.Format("{0} : {1}", item.Key, item.Value),
                    ForeColor = Color.White,
                    Tag = item.Key,
                    Filter = FilterType.OpenIn
                };
                itFilter.FilterClick += FilterOpenIn_FilterClick;
                flowLayoutSummary.Controls.Add(itFilter);
            }
            flowLayoutSummary.ResumeLayout();
            toolStripStatus.Text = string.Format("{0} : {1} {2}", EmieDocument.FileNameEmieDocument ?? Properties.Resources.UnselectedFile, EmieDocument.CountSites(), Properties.Resources.Sites);
            this.Cursor = oldcur;
        }

        private void Itp80_FilterClick(object sender, FilterEventArgs e)
        {
            var oldcur = this.Cursor;
            this.Cursor = Cursors.WaitCursor;
            if (CurrentFilter == FilterType.Port80)
            {
                ManagerFilter(FilterType.None, null);
            }
            else
            {
                ManagerFilter(FilterType.Port80, null);
            }
            ShowListUri();
            EnsureState();
            this.Cursor = oldcur;
        }

        private void Itdup_FilterClick(object sender, FilterEventArgs e)
        {
            var oldcur = this.Cursor;
            this.Cursor = Cursors.WaitCursor;
            if (CurrentFilter == FilterType.Duplicate)
            {
                ManagerFilter(FilterType.None, null);
            }
            else
            {
                ManagerFilter(FilterType.Duplicate, null);
            }
            ShowListUri();
            EnsureState();
            this.Cursor = oldcur;
        }

        private void FilterOpenIn_FilterClick(object sender, FilterEventArgs e)
        {
            var obj = (ImageAndLabel)sender;
            if (!e.FilterOn)
            {
                ManagerFilter(FilterType.OpenIn, obj.Tag.ToString());
            }
            else
            {
                ManagerFilter(FilterType.None, null);
            }
            ShowListUri();
            EnsureState();
        }

        private void FilterMode_FilterClick(object sender, FilterEventArgs e)
        {
            var obj = (ImageAndLabel)sender;
            if (!e.FilterOn)
            {
                ManagerFilter(FilterType.CompatMode, obj.Tag.ToString());
            }
            else
            {
                ManagerFilter(FilterType.None, null);
            }
            ShowListUri();
            EnsureState();
        }

        private void closeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!SavedFile && !string.IsNullOrEmpty(EmieDocument.FileNameEmieDocument))
            {
                if (this.ShowQuestion(Properties.Resources.ConfirmNotSave, AssemblyHelper.AssemblyTitle))
                {
                    saveToolStripMenuItem_Click(sender, e);
                }
            }
            SavedFile = false;
            var oldcur = this.Cursor;
            this.Cursor = Cursors.WaitCursor;
            CurrentFilter = FilterType.None;
            CurrentFilterValue = null;
            CurrentFind = string.Empty;
            CurrentFindIndex = -1;
            HistoryFind = new AutoCompleteStringCollection();
            TxtFindtoolStrip.AutoCompleteCustomSource = HistoryFind;
            EmieDocument.ResetEnvironment();
            listViewDataUrl.Items.Clear();
            listViewDataUrl.Groups.Clear();
            ShowSummary();
            toolStripStatus.Text = Properties.Resources.UnselectedFile;
            EnsureState();
            ManagerHotTracker.Clear();
            this.Cursor = oldcur;
        }

        private void updateDateCreatedOnSaveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Properties.Settings.Default.UpdateDateCreated = updateDateCreatedOnSaveToolStripMenuItem.Checked;
            Properties.Settings.Default.Save();
        }

        private void updateVersionOnSaveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Properties.Settings.Default.UpdateVersion = updateVersionOnSaveToolStripMenuItem.Checked;
            Properties.Settings.Default.Save();
        }

        [SuppressMessage("Microsoft.Design", "CA1031")]
        private void mergeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            openFileDialog.FileName = string.Empty;
            var result = openFileDialog.ShowDialog();
            if (result == DialogResult.OK)
            {
                try
                {
                    HelperEmie.ValidateSchemeSiteList(openFileDialog.FileName);
                }
                catch (Exception ex)
                {
                    this.ShowError(string.Format("{0}:{1}", Properties.Resources.ErrorValidateScheme, ex.Message), AssemblyHelper.AssemblyTitle);
                    return;
                }
                var oldcur = this.Cursor;
                try
                {
                    this.Cursor = Cursors.WaitCursor;

                    EmieDocument.ProgressChange += EmieDocument_ProgressChange;
                    var mergeresult = EmieDocument.OpenFileV2EmieDocument(
                        openFileDialog.FileName,
                        Properties.Settings.Default.RemoveP80,
                        Properties.Settings.Default.RemoveExtFilter?
                            Properties.Settings.Default.ExcludeExtension.Cast<string>().ToArray():
                            new string[] { },
                        Properties.Settings.Default.RemoveDomFilter?
                            Properties.Settings.Default.ExcludeDomains.Cast<string>().ToArray():
                            new string[] { }
                        );
                    MainProgressBar.Value = 0;
                    EmieDocument.ProgressChange -= EmieDocument_ProgressChange;
                    ManagerHotTracker.AddTraker(ActionTracker.MergeFile, Properties.Resources.NewSites, openFileDialog.FileName, mergeresult.NewItems);
                    if (mergeresult.ExcludeHost.Length > 0)
                    {
                        ManagerHotTracker.AddTraker(ActionTracker.MergeFile, Properties.Resources.RemoveDomainFilter, openFileDialog.FileName, mergeresult.ExcludeHost);
                    }
                    if (mergeresult.ExcludeExt.Length > 0)
                    {
                        ManagerHotTracker.AddTraker(ActionTracker.MergeFile, Properties.Resources.RemoveExtensionFilter, openFileDialog.FileName, mergeresult.ExcludeExt);
                    }
                    if (mergeresult.Port80.Length > 0)
                    {
                        ManagerHotTracker.AddTraker(ActionTracker.MergeFile, Properties.Resources.RemovePort80, openFileDialog.FileName, mergeresult.Port80);
                    }
                    if (mergeresult.Duplicates.Length > 0)
                    {
                        ManagerHotTracker.AddTraker(ActionTracker.MergeFile, Properties.Resources.DuplicateSites, openFileDialog.FileName, mergeresult.Duplicates);
                        this.Cursor = oldcur;
                        using (var frm = new FrmMerge())
                        {
                            frm.FileName = openFileDialog.FileName;
                            frm.DataMeger = mergeresult;
                            frm.ShowOption = ImportOption.Overwrite;
                            frm.TitleWindows = Properties.Resources.MergeSiteList;
                            frm.ShowDialog(this);
                        }
                    }
                    this.Cursor = Cursors.WaitCursor;
                    if (string.IsNullOrEmpty(EmieDocument.FileNameEmieDocument))
                    {
                        EmieDocument.FileNameEmieDocument = openFileDialog.FileName;
                    }
                    toolStripStatus.Text = string.Format("{0} : {1} {2}", EmieDocument.FileNameEmieDocument ?? Properties.Resources.UnselectedFile, EmieDocument.GetDataItems().Count(), Properties.Resources.Sites);
                    ManagerFilter(FilterType.None, null);
                    ShowListUri();
                    ShowSummary();
                    EnsureState();
                    SavedFile = false;
                }
                catch (Exception ex)
                {
                    this.Cursor = oldcur;
                    this.ShowError(string.Format("{0}:{1}", Properties.Resources.ErrorReadFile, ex.Message), AssemblyHelper.AssemblyTitle);
                }
                this.Cursor = oldcur;
            }
        }

        private void importSiteDiscoveryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            EmieDocument.ClearTempEmieDocument();
            DialogResult result;
            using (var frm = new FrmLoadSiteDiscovery())
            {
                result = frm.ShowDialog(this);
            }
            if (result == DialogResult.OK)
            {
                EmieDocument.ProgressChange += EmieDocument_ProgressChange;
                var dataMerge = EmieDocument.OpenStreamV2EmieDocument(EmieDocument.TempEmieDocument,
                        Properties.Settings.Default.RemoveP80,
                        Properties.Settings.Default.RemoveExtFilter ?
                            Properties.Settings.Default.ExcludeExtension.Cast<string>().ToArray() :
                            new string[] { },
                        new string[] { }
                        );
                MainProgressBar.Value = 0;
                EmieDocument.ProgressChange -= EmieDocument_ProgressChange;

                EmieDocument.ClearTempEmieDocument();
                ManagerHotTracker.AddTraker(ActionTracker.ImportSiteDiscovery, Properties.Resources.NewSites, Properties.Resources.ImportedSiteDiscovery, dataMerge.NewItems);

                if (dataMerge.ExcludeExt.Length > 0)
                {
                    ManagerHotTracker.AddTraker(ActionTracker.ImportSiteDiscovery, Properties.Resources.RemoveExtensionFilter, Properties.Resources.ImportedSiteDiscovery, dataMerge.ExcludeExt);
                }
                if (dataMerge.Port80.Length > 0)
                {
                    ManagerHotTracker.AddTraker(ActionTracker.ImportSiteDiscovery, Properties.Resources.RemovePort80, Properties.Resources.ImportedSiteDiscovery, dataMerge.Port80);
                }
                if (dataMerge.Duplicates.Count() > 0)
                {
                    ManagerHotTracker.AddTraker(ActionTracker.ImportSiteDiscovery, Properties.Resources.DuplicateSites, Properties.Resources.ImportedSiteDiscovery, dataMerge.Duplicates);
                }
                using (var frmMerge = new FrmMerge())
                {
                    frmMerge.FileName = Properties.Resources.ImportedSiteDiscovery;
                    frmMerge.DataMeger = dataMerge;
                    frmMerge.ShowOption = ImportOption.Overwrite;
                    frmMerge.TitleWindows = Properties.Resources.MergeFromSiteDiscovery;
                    frmMerge.ShowDialog(this);
                }
                if (string.IsNullOrEmpty(EmieDocument.FileNameEmieDocument))
                {
                    var newfile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), Properties.Resources.DefaultNewFileName);
                    EmieDocument.FileNameEmieDocument = newfile;
                }
                var oldcur = this.Cursor;
                this.Cursor = Cursors.WaitCursor;
                ManagerFilter(FilterType.None, null);
                ShowListUri();
                ShowSummary();
                EnsureState();
                SavedFile = false;
                this.Cursor = oldcur;
            }
            else
            {
                EmieDocument.ClearTempEmieDocument();
            }
        }

        private void UrlEndsWithFilterToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (var frm = new FrmEditFilterExtension())
            {
                frm.ShowDialog(this);
            }
        }

        private void domainFilterToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (var frm = new FrmEditFilterDomains())
            {
                frm.ShowDialog(this);
            }
        }

        private void changeVersionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (var frm = new FrmChangeVersion())
            {
                var result = frm.ShowDialog(this);
                if (result == DialogResult.OK)
                {
                    SavedFile = false;
                }
            }
            ShowSummary();
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (var frm = new AboutBox())
            {
                frm.ShowDialog(this);
            }
            ShowSummary();
        }

        private void removeSpecificPort80ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var oldcur = this.Cursor;
            this.Cursor = Cursors.WaitCursor;
            ManagerHotTracker.AddTraker(ActionTracker.RemovePort80, Properties.Resources.RemovePort80, "", EmieDocument.FindSiteSpecificPort80());
            if (EmieDocument.RemoveSpecificPort80())
            {
                SavedFile = false;
            }
            EmieDocument.FindDuplicateSite();
            ManagerFilter(FilterType.None, null);
            ShowListUri();
            ShowSummary();
            EnsureState();
            this.Cursor = oldcur;
        }

        private void listViewDataUrl_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                ListViewHitTestInfo hit = listViewDataUrl.HitTest(e.Location);
                if (hit.SubItem != null)
                {
                    var value = hit.SubItem.Text;
                    var columnindex = hit.Item.SubItems.IndexOf(hit.SubItem);
                    if (columnindex == 0)
                    {
                        ContextToolStripMenuEditSite.Visible = (listViewDataUrl.SelectedItems.Count == 1);
                        ContextToolStripMenuRemoveSite.Visible = true;
                        contextMenuActions.Tag = hit.Item;
                        contextMenuActions.Show(listViewDataUrl, e.Location);
                    }
                    else if (columnindex == 1)
                    {
                        foreach (ToolStripMenuItem item in contextMenuDocMode.Items)
                        {
                            item.Checked = false;
                            if (item.Text == value && listViewDataUrl.SelectedItems.Count == 1)
                            {
                                item.Checked = true;
                            }
                        }
                        contextMenuDocMode.Tag = hit.Item;
                        contextMenuDocMode.Show(listViewDataUrl, e.Location);
                    }
                    else if (columnindex == 2)
                    {
                        foreach (ToolStripMenuItem item in contextMenuOpenIn.Items)
                        {
                            item.Checked = false;
                            if (item.Text == value && listViewDataUrl.SelectedItems.Count == 1)
                            {
                                item.Checked = true;
                            }
                        }
                        contextMenuOpenIn.Tag = hit.Item;
                        contextMenuOpenIn.Show(listViewDataUrl, e.Location);
                    }
                }
            }
        }

        private void listViewDataUrl_KeyUp(object sender, KeyEventArgs e)
        {
            if (Keys.Delete == e.KeyCode && listViewDataUrl.SelectedItems.Count > 0)
            {
                var respOk = this.ShowQuestion(string.Format(Properties.Resources.ConfirmDelete, listViewDataUrl.SelectedItems.Count), AssemblyHelper.AssemblyTitle);
                if (respOk)
                {
                    var oldcur = this.Cursor;
                    this.Cursor = Cursors.WaitCursor;
                    var itemsDel = new List<IEModeDataItem>();
                    var posVisible = listViewDataUrl.Items.Count;
                    foreach (ListViewItem item in listViewDataUrl.SelectedItems)
                    {
                        if (posVisible > item.Index)
                        {
                            posVisible = item.Index;
                        }
                        itemsDel.Add((IEModeDataItem)item.Tag);
                    }
                    ManagerHotTracker.AddTraker(ActionTracker.RemoveSite, Properties.Resources.RemoveSite, "", itemsDel);
                    var qtd = EmieDocument.RemoveSites(itemsDel);
                    EmieDocument.FindDuplicateSite();
                    if (CurrentFilter == FilterType.Duplicate && EmieDocument.CountSiteDuplicate() == 0)
                    {
                        ManagerFilter(FilterType.None, null);
                    }
                    ShowListUri();
                    ShowSummary();
                    EnsureState();

                    if (posVisible >= listViewDataUrl.Items.Count)
                    {
                        posVisible = listViewDataUrl.Items.Count - 1;
                    }
                    if (posVisible > 0)
                    {
                        listViewDataUrl.TopItem = listViewDataUrl.Items[posVisible];
                        listViewDataUrl.EnsureVisible(posVisible);
                    }
                    this.Cursor = oldcur;
                    if (qtd > 0)
                    {
                        SavedFile = false;
                        this.ShowInformation(string.Format(Properties.Resources.QtdRemoved, qtd), AssemblyHelper.AssemblyTitle);
                    }
                }
            }
        }

        private void ManagerFilter(FilterType filter, string value)
        {
            CurrentFilter = filter;
            CurrentFilterValue = value;
        }

        private void PctClearFilter_Click(object sender, EventArgs e)
        {

            var oldcur = this.Cursor;
            this.Cursor = Cursors.WaitCursor;
            ManagerFilter(FilterType.None, null);
            ShowListUri();
            EnsureState();
            this.Cursor = oldcur;
        }

        private void ContextToolStripMenuRemoveSite_Click(object sender, EventArgs e)
        {
            listViewDataUrl_KeyUp(listViewDataUrl, new KeyEventArgs(Keys.Delete));
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            saveFileDialog.FileName = EmieDocument.FileNameEmieDocument;
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                var oldfile = string.Empty;
                if (Properties.Settings.Default.BackupOldVersion)
                {
                    if (!string.IsNullOrEmpty(EmieDocument.FileNameEmieDocument))
                    {
                        var bkpfile = Path.GetFileNameWithoutExtension(EmieDocument.FileNameEmieDocument);
                        bkpfile = string.Format("{0}{1}{2}.{3}", bkpfile, "_V", EmieDocument.VersionEmieDocument, saveFileDialog.DefaultExt);
                        bkpfile = Path.Combine(Path.GetDirectoryName(EmieDocument.FileNameEmieDocument), bkpfile);
                        if (File.Exists(EmieDocument.FileNameEmieDocument))
                        {
                            File.Copy(EmieDocument.FileNameEmieDocument, bkpfile, true);
                        }
                        oldfile = bkpfile;
                    }
                }

                if (Properties.Settings.Default.UpdateVersion)
                {
                    ManagerHotTracker.AddTraker(ActionTracker.ChangeVersion, Properties.Resources.ChangedVersion, string.Format("{0} => {1}", EmieDocument.VersionEmieDocument, EmieDocument.VersionEmieDocument + 1), null);
                    EmieDocument.UpdateVersionEmieDocument(EmieDocument.VersionEmieDocument + 1);
                }
                if (Properties.Settings.Default.UpdateDateCreated)
                {
                    EmieDocument.UpdateDateCreatedEmieDocument();
                }

                HelperEmie.SaveToV2file(EmieDocument.GetDataItems(),
                    saveFileDialog.FileName,
                    AssemblyHelper.AssemblyProduct,
                    AssemblyHelper.AssemblyVersion,
                    EmieDocument.DateCreatedEmieDocument,
                    EmieDocument.VersionEmieDocument.ToString());

                EmieDocument.FileNameEmieDocument = saveFileDialog.FileName;
                ShowSummary();
                SavedFile = true;
                ManagerHotTracker.AddTraker(ActionTracker.SaveFile, Properties.Resources.FileSaved, saveFileDialog.FileName, EmieDocument.GetDataItems());
                if (!string.IsNullOrEmpty(oldfile))
                {
                    this.ShowInformation(string.Format(Properties.Resources.OldSitesWasSaved, oldfile), AssemblyHelper.AssemblyTitle);
                }
                this.ShowInformation(string.Format(Properties.Resources.SitesWasSaved, saveFileDialog.FileName), AssemblyHelper.AssemblyTitle);
            }
        }

        private void simplifyingListOfSitesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var oldcur = this.Cursor;
            this.Cursor = Cursors.WaitCursor;
            var result = new ConcurrentBag<Dictionary<string, List<IEModeDataItem>>>();
            var domains = EmieDocument.GetDomains(null, false);
            MainProgressBar.Maximum = domains.Count();
            foreach (var item in domains)
            {
                MainProgressBar.Increment(1);
                var sites = EmieDocument.GetSitesByDomain(item);
                var simply = EmieDocument.Sanitize(sites);
                if (simply.Count() > 0)
                {
                    result.Add(simply);
                }
            };
            MainProgressBar.Value = 0;
            this.Cursor = oldcur;
            if (result.Count == 0)
            {
                this.ShowInformation(Properties.Resources.NotFoundSanitize, AssemblyHelper.AssemblyTitle);
                return;
            }
            DialogResult resultfrm;
            IEModeDataItem[] resultSanitaze = null;
            using (var frm = new FrmSanitize())
            {
                frm.DataSanitaze = result.ToList();
                resultfrm = frm.ShowDialog(this);
                if (resultfrm == DialogResult.OK)
                {
                    resultSanitaze = frm.ResultSanitaze;
                }
            }
            var qtd = 0;
            if (resultfrm == DialogResult.OK)
            {
                this.Cursor = Cursors.WaitCursor;
                ManagerHotTracker.AddTraker(ActionTracker.Sanitize, Properties.Resources.SanitizeListSites, "", resultSanitaze);
                qtd = EmieDocument.RemoveSites(resultSanitaze);
                EmieDocument.FindDuplicateSite();
                ManagerFilter(FilterType.None, null);
                ShowListUri();
                ShowSummary();
                EnsureState();
                this.Cursor = oldcur;
            }
            if (qtd > 0)
            {
                SavedFile = false;
                this.ShowInformation(string.Format(Properties.Resources.QtdRemoved, qtd), AssemblyHelper.AssemblyTitle);
            }
        }

        private void listViewDataUrl_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            var qtd = listViewDataUrl.SelectedIndices.Count;
            toolStripButtonEditItem.Enabled = (qtd == 1);
            toolStripButtonRemoveItem.Enabled = (qtd >= 1);
        }

        private void toolStripButtonNewItem_Click(object sender, EventArgs e)
        {
            DialogResult result;
            using (var frm = new FrmAddEditItem())
            {
                frm.Text = Properties.Resources.AddNewSite;
                frm.NewSite = true;
                result = frm.ShowDialog(this);
            }
            if (result == DialogResult.OK)
            {
                if (string.IsNullOrEmpty(EmieDocument.FileNameEmieDocument))
                {
                    var newfile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), Properties.Resources.DefaultNewFileName);
                    EmieDocument.FileNameEmieDocument = newfile;
                }
                SavedFile = false;
                var oldcur = this.Cursor;
                this.Cursor = Cursors.WaitCursor;
                ManagerFilter(FilterType.None, null);
                ShowListUri();
                ShowSummary();
                EnsureState();
                this.Cursor = oldcur;
            }
        }

        private void toolStripButtonEditItem_Click(object sender, EventArgs e)
        {
            DialogResult result;
            using (var frm = new FrmAddEditItem())
            {
                frm.Text = Properties.Resources.EditSeletedSite;
                frm.NewSite = false;
                var oriItem = (IEModeDataItem)listViewDataUrl.SelectedItems[0].Tag;
                frm.DataSite.Uri = oriItem.Uri;
                frm.DataSite.OpenIn = oriItem.OpenIn;
                frm.DataSite.CompatMode = oriItem.CompatMode;
                frm.DataSite.Comment = oriItem.Comment;
                result = frm.ShowDialog(this);
            }

            if (result == DialogResult.OK)
            {
                var oldcur = this.Cursor;
                this.Cursor = Cursors.WaitCursor;
                EmieDocument.FindDuplicateSite();
                ManagerFilter(FilterType.None, null);
                ShowListUri();
                ShowSummary();
                EnsureState();
                SavedFile = false;
                this.Cursor = oldcur;
            }
        }

        private void ContextToolStripMenuEditSite_Click(object sender, EventArgs e)
        {
            toolStripButtonEditItem_Click(sender, e);
        }

        private void FindTextInSites()
        {
            var textfind = TxtFindtoolStrip.Text.Trim();
            if (string.IsNullOrEmpty(textfind))
            {
                CurrentFind = string.Empty;
                CurrentFindIndex = -1;
                FindnextToolStripMenuItem.Enabled = !string.IsNullOrEmpty(CurrentFind);
                FindpreviousToolStripMenuItem.Enabled = !string.IsNullOrEmpty(CurrentFind);
                return;
            }
            var find = listViewDataUrl.Items.Cast<ListViewItem>().
                    FirstOrDefault(s => s.Text.ToLower().Contains(textfind.ToLower()));
            if (find?.Index >= 0)
            {
                CurrentFind = textfind;
                CurrentFindIndex = find.Index;
                listViewDataUrl.SelectedItems.Clear();
                find.Selected = true;
                listViewDataUrl.EnsureVisible(CurrentFindIndex);
                if (!HistoryFind.Cast<string>().Any(h => h.ToLower() == CurrentFind.ToLower()))
                {
                    HistoryFind.Add(CurrentFind);
                }
            }
            else
            {
                CurrentFind = string.Empty;
                CurrentFindIndex = -1;
            }
            TxtFindtoolStrip.Text = CurrentFind;
            FindnextToolStripMenuItem.Enabled = !string.IsNullOrEmpty(CurrentFind);
            FindpreviousToolStripMenuItem.Enabled = !string.IsNullOrEmpty(CurrentFind);
            clearHistoryToolStripMenuItem.Enabled = (HistoryFind.Count > 0);
            listViewDataUrl.Focus();
        }

        private void clearHistoryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TxtFindtoolStrip.Text = string.Empty;
            HistoryFind = new AutoCompleteStringCollection();
            TxtFindtoolStrip.AutoCompleteCustomSource = HistoryFind;
            CurrentFind = string.Empty;
            CurrentFindIndex = -1;
            FindnextToolStripMenuItem.Enabled = !string.IsNullOrEmpty(CurrentFind);
            FindpreviousToolStripMenuItem.Enabled = !string.IsNullOrEmpty(CurrentFind);
            clearHistoryToolStripMenuItem.Enabled = false;
        }

        private void FindnextToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var textfind = string.Empty;
            if (string.IsNullOrEmpty(CurrentFind))
            {
                textfind = TxtFindtoolStrip.Text.Trim();
            }
            else
            {
                textfind = CurrentFind;
            }
            if (string.IsNullOrEmpty(textfind))
            {
                CurrentFind = string.Empty;
                CurrentFindIndex = -1;
                FindnextToolStripMenuItem.Enabled = !string.IsNullOrEmpty(CurrentFind);
                FindpreviousToolStripMenuItem.Enabled = !string.IsNullOrEmpty(CurrentFind);
                return;
            }
            TxtFindtoolStrip.Text = textfind;
            var find = listViewDataUrl.Items.Cast<ListViewItem>()
                .Where(s => s.Index > CurrentFindIndex)
                .FirstOrDefault(s => s.Text.ToLower().Contains(textfind.ToLower()));
            if (!(find?.Index >= 0))
            {
                CurrentFindIndex = -1;
                find = listViewDataUrl.Items.Cast<ListViewItem>()
                    .Where(s => s.Index > CurrentFindIndex)
                    .FirstOrDefault(s => s.Text.ToLower().Contains(textfind.ToLower()));
            }
            if (find?.Index >= 0)
            {
                CurrentFind = textfind;
                CurrentFindIndex = find.Index;
                listViewDataUrl.SelectedItems.Clear();
                find.Selected = true;
                listViewDataUrl.EnsureVisible(CurrentFindIndex);
                if (!HistoryFind.Cast<string>().Any(h => h.ToLower() == CurrentFind.ToLower()))
                {
                    HistoryFind.Add(CurrentFind);
                }
            }
            TxtFindtoolStrip.Text = CurrentFind;
            FindnextToolStripMenuItem.Enabled = !string.IsNullOrEmpty(CurrentFind);
            FindpreviousToolStripMenuItem.Enabled = !string.IsNullOrEmpty(CurrentFind);
            listViewDataUrl.Focus();
        }

        private void FindpreviousToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var textfind = string.Empty;
            if (string.IsNullOrEmpty(CurrentFind))
            {
                textfind = TxtFindtoolStrip.Text.Trim();
            }
            else
            {
                textfind = CurrentFind;
            }
            if (string.IsNullOrEmpty(textfind))
            {
                CurrentFind = string.Empty;
                CurrentFindIndex = -1;
                FindnextToolStripMenuItem.Enabled = !string.IsNullOrEmpty(CurrentFind);
                FindpreviousToolStripMenuItem.Enabled = !string.IsNullOrEmpty(CurrentFind);
                return;
            }
            TxtFindtoolStrip.Text = textfind;
            var find = listViewDataUrl.Items.Cast<ListViewItem>()
                .Where(s => s.Index < CurrentFindIndex)
                .OrderByDescending(s => s.Index)
                .FirstOrDefault(s => s.Text.ToLower().Contains(textfind.ToLower()));
            if (!(find?.Index >= 0))
            {
                CurrentFindIndex = listViewDataUrl.Items.Count;
                find = listViewDataUrl.Items.Cast<ListViewItem>()
                    .Where(s => s.Index < CurrentFindIndex)
                    .OrderByDescending(s => s.Index)
                    .FirstOrDefault(s => s.Text.ToLower().Contains(textfind.ToLower()));
            }

            if (find?.Index >= 0)
            {
                CurrentFind = textfind;
                CurrentFindIndex = find.Index;
                listViewDataUrl.SelectedItems.Clear();
                find.Selected = true;
                listViewDataUrl.EnsureVisible(CurrentFindIndex);
                if (!HistoryFind.Cast<string>().Any(h => h.ToLower() == CurrentFind.ToLower()))
                {
                    HistoryFind.Add(CurrentFind);
                }
            }
            TxtFindtoolStrip.Text = CurrentFind;
            FindnextToolStripMenuItem.Enabled = !string.IsNullOrEmpty(CurrentFind);
            FindpreviousToolStripMenuItem.Enabled = !string.IsNullOrEmpty(CurrentFind);
            listViewDataUrl.Focus();
        }

        private void TxtFindtoolStrip_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                FindTextInSites();
            }
        }

        private void listViewDataUrl_DoubleClick(object sender, EventArgs e)
        {
            if (listViewDataUrl.SelectedIndices.Count == 1)
            {
                toolStripButtonEditItem_Click(sender, e);
            }
        }

        private void toolStripButtonDomains_Click(object sender, EventArgs e)
        {
            var oldcur = this.Cursor;
            this.Cursor = Cursors.WaitCursor;
            string[] resultRemoveDomains = null;
            DialogResult result;
            using (var frm = new FrmRemoveDomains())
            {
                frm.DataRemoveDomains = EmieDocument.GetDomains();
                result = frm.ShowDialog(this);
                if (result == DialogResult.OK)
                {
                    resultRemoveDomains = frm.ResultRemoveDomains;
                }
            }
            this.Cursor = oldcur;
            var qtd = 0;
            if (result == DialogResult.OK)
            {
                this.Cursor = Cursors.WaitCursor;
                var itemToDelte = EmieDocument.GetItemsByDomains(resultRemoveDomains);
                ManagerHotTracker.AddTraker(ActionTracker.RemoveDomain, Properties.Resources.RemoveDomains, "", itemToDelte);
                qtd = EmieDocument.RemoveDomains(itemToDelte);
                ManagerFilter(FilterType.None, null);
                ShowListUri();
                ShowSummary();
                EnsureState();
            }
            this.Cursor = oldcur;
            if (qtd > 0)
            {
                SavedFile = false;
                this.ShowInformation(string.Format(Properties.Resources.QtdRemoved, qtd), AssemblyHelper.AssemblyTitle);
            }
        }

        private void BackupOldVersionOnSaveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Properties.Settings.Default.BackupOldVersion = BackupOldVersionOnSaveToolStripMenuItem.Checked;
            Properties.Settings.Default.Save();
        }

        [SuppressMessage("Microsoft.Reliability", "CA2000")]
        private void toolStripButtonCopyDomains_Click(object sender, EventArgs e)
        {
            var frm = new FrmCopyDomain();
            frm.DataCopyDomains = EmieDocument.GetDomains();
            if (frm.ShowDialog(this) == DialogResult.OK)
            {
                var oldcur = this.Cursor;
                this.Cursor = Cursors.WaitCursor;
                var newdomainResult = EmieDocument.AddSitesToPublicDomain(EmieDocument.GetSitesByDomain(frm.LocalDomain), frm.PublicDomain, frm.RemovePublicPort);
                ManagerHotTracker.AddTraker(ActionTracker.CopyDomain, Properties.Resources.CopyDomains, frm.LocalDomain, newdomainResult);
                ManagerFilter(FilterType.None, null);
                ShowListUri();
                ShowSummary();
                EnsureState();
                this.Cursor = oldcur;
                var qtd = newdomainResult.Count();
                if (qtd > 0)
                {
                    SavedFile = false;
                    this.ShowInformation(string.Format(Properties.Resources.AddedSitesNewDomain, qtd, frm.PublicDomain), AssemblyHelper.AssemblyTitle);
                }
            }
        }

        private void singleUrlAtDomainToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var oldcur = this.Cursor;
            this.Cursor = Cursors.WaitCursor;
            foreach (ToolStripMenuItem item in customFiltersToolStripMenuItem.DropDownItems)
            {
                if (item.Tag.ToString() != "SingleUrl")
                {
                    item.Checked = false;
                }
            }
            toolStripLblFilterCustom.Text = string.Empty;
            if (singleUrlAtDomainToolStripMenuItem.Checked)
            {
                ManagerFilter(FilterType.Custom, "SingleUrl");
                toolStripLblFilterCustom.Text = singleUrlAtDomainToolStripMenuItem.Text;
            }
            else
            {
                ManagerFilter(FilterType.None, null);
            }
            ShowListUri();
            EnsureState();
            this.Cursor = oldcur;

        }

        private void urlRootWithModeIE11ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var oldcur = this.Cursor;
            this.Cursor = Cursors.WaitCursor;
            foreach (ToolStripMenuItem item in customFiltersToolStripMenuItem.DropDownItems)
            {
                if (item.Tag.ToString() != "UrlRootIE11")
                {
                    item.Checked = false;
                }
            }
            toolStripLblFilterCustom.Text = string.Empty;
            if (urlRootWithModeIE11ToolStripMenuItem.Checked)
            {
                ManagerFilter(FilterType.Custom, "UrlRootIE11");
                toolStripLblFilterCustom.Text = urlRootWithModeIE11ToolStripMenuItem.Text;
            }
            else
            {
                ManagerFilter(FilterType.None, null);
            }
            ShowListUri();
            EnsureState();
            this.Cursor = oldcur;
        }

        private void checkNewVersionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var oldcur = this.Cursor;
            this.Cursor = Cursors.WaitCursor;
            var newver = AssemblyHelper.CheckVersion();
            this.Cursor = oldcur;
            if (!string.IsNullOrEmpty(newver))
            {
                NewNotify.Visible = true;
                if (this.ShowQuestion(string.Format(Properties.Resources.ExistNewVersion, resultCheckVer), AssemblyHelper.AssemblyTitle))
                {
                    System.Diagnostics.Process.Start(AssemblyHelper.AppSite);
                }
            }
            else
            {
                if (newver != null)
                {
                    this.ShowInformation(Properties.Resources.NoNewVersion, AssemblyHelper.AssemblyTitle);
                }
                else
                {
                    this.ShowInformation(string.Format(Properties.Resources.ErroNewVersion, AssemblyHelper.AppSite), AssemblyHelper.AssemblyTitle);
                }
            }
        }

        private void NewNotify_Click(object sender, EventArgs e)
        {
            if (this.ShowQuestion(string.Format(Properties.Resources.ExistNewVersion, resultCheckVer), AssemblyHelper.AssemblyTitle))
            {
                System.Diagnostics.Process.Start(AssemblyHelper.AppSite);
            }
        }

        private void removePort80atFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Properties.Settings.Default.RemoveP80 = removePort80atFileToolStripMenuItem.Checked;
            Properties.Settings.Default.Save();
        }

        private void trackerActionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (var frm = new FrmTracker())
            {
                frm.DataTracker = ManagerHotTracker.DataTracker();
                frm.ShowDialog(this);
            }
        }

        private void enabledTrackerActionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Properties.Settings.Default.EnableHotTracker = enabledTrackerActionToolStripMenuItem.Checked;
            Properties.Settings.Default.Save();
            trackerActionToolStripMenuItem.Visible = Properties.Settings.Default.EnableHotTracker;
            toolStripSeparatorTracker.Visible = Properties.Settings.Default.EnableHotTracker;
            if (!Properties.Settings.Default.EnableHotTracker)
            {
                ManagerHotTracker.Clear();
            }
            ManagerHotTracker.TrackerEnable(Properties.Settings.Default.EnableHotTracker);
        }

        private void removeUrlEndswithExtensionFilterToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Properties.Settings.Default.RemoveExtFilter = removeUrlEndswithExtensionFilterToolStripMenuItem.Checked;
            Properties.Settings.Default.Save();
        }

        private void removeUrlWithDomainFilterToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Properties.Settings.Default.RemoveDomFilter = removeUrlWithDomainFilterToolStripMenuItem.Checked;
            Properties.Settings.Default.Save();
        }

        private void trailingSlashesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var oldcur = this.Cursor;
            this.Cursor = Cursors.WaitCursor;
            foreach (ToolStripMenuItem item in customFiltersToolStripMenuItem.DropDownItems)
            {
                if (item.Tag.ToString() != "Slash")
                {
                    item.Checked = false;
                }
            }
            toolStripLblFilterCustom.Text = string.Empty;
            if (trailingSlashesToolStripMenuItem.Checked)
            {
                ManagerFilter(FilterType.Custom, "Slash");
                toolStripLblFilterCustom.Text = trailingSlashesToolStripMenuItem.Text;
            }
            else
            {
                ManagerFilter(FilterType.None, null);
            }
            ShowListUri();
            EnsureState();
            this.Cursor = oldcur;
        }
    }
}
